﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Teigha.Core
{
	public class MemoryManager
	{
		public static MemoryManager GetMemoryManager()
		{
			if (MemoryManager.mMngr == null)
			{
				lock (MemoryManager.memLocker)
				{
					if (MemoryManager.mMngr == null)
					{
						MemoryManager.mMngr = new MemoryManager();
					}
				}
			}
			return MemoryManager.mMngr;
		}

		private MemoryManager()
		{
			this.TransList = new List<MemoryTransaction>();
		}

		public MemoryTransaction GetCurrentTransaction()
		{
			if (this.TransList.Count == 0)
			{
				return null;
			}
			return this.TransList.Last<MemoryTransaction>();
		}

		public MemoryTransaction StartTransaction()
		{
			MemoryTransaction memoryTransaction = new MemoryTransaction();
			this.TransList.Add(memoryTransaction);
			return memoryTransaction;
		}

		public void StopTransaction(MemoryTransaction value)
		{
			if (!this.TransList.Contains(value))
			{
				return;
			}
			MemoryTransaction memoryTransaction;
			for (memoryTransaction = this.TransList.Last<MemoryTransaction>(); memoryTransaction != value; memoryTransaction = this.TransList.Last<MemoryTransaction>())
			{
				this.TransList.Remove(memoryTransaction);
				memoryTransaction.DeleteObjects();
			}
			this.TransList.Remove(memoryTransaction);
			memoryTransaction.DeleteObjects();
		}

		public void StopAll()
		{
			for (int i = this.TransList.Count; i > 0; i = this.TransList.Count)
			{
				MemoryTransaction memoryTransaction = this.TransList.Last<MemoryTransaction>();
				this.TransList.Remove(memoryTransaction);
				memoryTransaction.DeleteObjects();
			}
		}

		private static MemoryManager mMngr = null;

		private static object memLocker = new object();

		private List<MemoryTransaction> TransList;
	}
}
